$(function(){
	var cache = [];
	// init competition day grid
	$.get('/s/workflow/service?action=listSession&id='+$("#cid").val(), function(data) {
		
		$("#grid").kendoGrid({
	        scrollable: true,
	        sortable: false,
	        filterable: false,
	        pageable: {
	            input: false,
	            numeric: false
	        },
	        columns: [
	            { field: "date", title: "Date", width: "100px",template: "#= date #"},
	            { field: "morningSession", title: "Morning", width: "150px",	template: '# if(morning){ # <button data-slot="morningSession">Available: #= morningSession.availUmpire.length # 	/ Confirmed: #= morningSession.confirmedUmpire.length # </button> #}#' },
	            { field: "afternoonSession", title: "Afternoon", width: "150px",template: '# if(afternoon){ # <button data-slot="afternoonSession">Available: #= afternoonSession.availUmpire.length || 0 # / Confirmed: #= afternoonSession.confirmedUmpire.length # </button> #}#' },
	            { field: "eveningSession", title:"Evening", width: "150px",		template: '# if(evening){ # <button data-slot="eveningSession">Available: #= eveningSession.availUmpire.length || 0 # 	/ Confirmed: #= eveningSession.confirmedUmpire.length # </button> #}#' },
	        ],
	        
	        dataSource:{
	        	data: data
	        }
		});
	});
	
	// actions
    var window = $("#dateslotwin");
    if (!window.data("kendoWindow")) {
        window.kendoWindow({
            width: "800px",
            title: "Select Umpires",
        });
    }
    window.data("kendoWindow").close();

	$("#grid").delegate("button", "click", function(){
		var rowIndex = $(this).closest('td').parent()[0].sectionRowIndex;
		var slot = $(this).data("slot");
		var data = $("#grid").data("kendoGrid").dataItem("tr:eq("+(rowIndex+1)+")");
		cache["data"] = data;
		cache["slot"] = slot;
		cache["sessionKey"] = data[slot].key;
		
		$.ajax({
			url: "/s/workflow/service?action=listUmpires",
			data:{
				avail: data[slot].availUmpire.join(','),
				confirmed: data[slot].confirmedUmpire.join(',')
			},
			success: function(umpires){
				cache["umpires"] = umpires;
				
                var availDataSource = new kendo.data.DataSource({
                    data: umpires.avail,
                    pageSize: 7
                });
                var confirmDataSource = new kendo.data.DataSource({
                    data: umpires.confirmed,
                    pageSize: 7
                });
                
                $("#pager1").kendoPager({
                    dataSource: availDataSource
                    });
                $("#pager2").kendoPager({
                	dataSource: confirmDataSource
                });
                $("#availlistview").kendoListView({
                	dataSource: availDataSource,
                	selectable: "multiple",
                	template: kendo.template($("#listtemplate").html())
                });
                $("#confirmlistview").kendoListView({
                	dataSource: confirmDataSource,
                	selectable: "multiple",
                	template: kendo.template($("#listtemplate").html())
                });

                var win = window.data("kendoWindow");
                win.center();
                win.title("Select Umpires for " + data.date + " " + slot);
                win.open();
			}
		});
	});
	
    var moveRight = $("#moveRight")
    .bind("click", function() {
        var availListView = $("#availlistview").data("kendoListView");
        var confirmListView = $("#confirmlistview").data("kendoListView");
        var selected = availListView.select();
        var index = $(selected[0]).index();
        
        var confirmedCu = cache["umpires"].confirmed,
        	availableCu = cache["umpires"].avail;
        for(var i=0;i<selected.length;i++){
        	confirmedCu.push(availableCu[index]);
        	availableCu.splice(index,1);
        }
        var availDataSource = new kendo.data.DataSource({
            data: availableCu,
            pageSize: 7
        });
        availListView.setDataSource(availDataSource);
        var confirmDataSource = new kendo.data.DataSource({
            data: confirmedCu,
            pageSize: 7
        });
        confirmListView.setDataSource(confirmDataSource);
    });
    
    var moveLeft = $("#moveLeft")
    .bind("click", function() {
        var availListView = $("#availlistview").data("kendoListView");
        var confirmListView = $("#confirmlistview").data("kendoListView");
        var selected = confirmListView.select();
        var index = $(selected[0]).index();
        
        var confirmedCu = cache["umpires"].confirmed,
    		availableCu = cache["umpires"].avail;
        for(var i=0;i<selected.length;i++){
        	availableCu.push(confirmedCu[index]);
        	confirmedCu.splice(index,1);
        }
        var availDataSource = new kendo.data.DataSource({
            data: availableCu,
            pageSize: 7
        });
        availListView.setDataSource(availDataSource);
        var confirmDataSource = new kendo.data.DataSource({
            data: confirmedCu,
            pageSize: 7
        });
        confirmListView.setDataSource(confirmDataSource);
    });
    
    $("#save_assignment")
    .bind("click", function() {
        var avail = [], confirmed = [];
        
        $("#availlistview").find(".umpireItem").each(function(){
        	avail.push($(this).data("id"));
        });
        
        $("#confirmlistview").find(".umpireItem").each(function(){
        	confirmed.push($(this).data("id"));
        })

    	$.ajax({
            url: '/s/workflow/service?action=updateSession',
            data: {
            	sessionKey: cache["sessionKey"] ,
    			avail: avail.join(","),
    			confirmed: confirmed.join(",")
            },
            type: "POST",
            success: function() { window.data("kendoWindow").close(); location.reload(false);}
         });
    });
    
    
});



function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
 function sendEmailConfirmation(){
	var competitionId = $("#cid").val();
	$.ajax({
	    url: '/s/workflow/service?action=sendConfirmationEmail',
	    type: "POST",
	    data: {id: competitionId},
	    success: function() { alert("Confirmation Email Sent");}
	 });
 }
